<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/dute_favicon_32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/dute_favicon_16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="manifest" href="/images/manifest.json">
  <meta name="msapplication-config" content="/images/browserconfig.xml">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">
  <meta name="google-site-verification" content="mpI5dkydstZXl6UcDCppqktXK0bbvqdZ6LkZ3KNk4Iw">
  <meta name="baidu-site-verification" content="code-a1LksZX2Ds">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"whitestore.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="设计模式装饰器模式">
<meta property="og:type" content="article">
<meta property="og:title" content="浅谈设计模式 - 装饰器模式（五）">
<meta property="og:url" content="https://whitestore.top/2021/02/14/strategymodal/index.html">
<meta property="og:site_name" content="爱看书的阿东">
<meta property="og:description" content="设计模式装饰器模式">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210207162333.png?ynotemdtimestamp=1613223296738">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210207230255.png?ynotemdtimestamp=1613223296738">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210208001255.png?ynotemdtimestamp=1613223296738">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210208114348.png?ynotemdtimestamp=1613223296738">
<meta property="article:published_time" content="2021-02-14T03:40:16.000Z">
<meta property="article:modified_time" content="2023-07-16T06:28:09.265Z">
<meta property="article:author" content="阿东">
<meta property="article:tag" content="装饰器模式">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210207162333.png?ynotemdtimestamp=1613223296738">

<link rel="canonical" href="https://whitestore.top/2021/02/14/strategymodal/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>浅谈设计模式 - 装饰器模式（五） | 爱看书的阿东</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="爱看书的阿东" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">爱看书的阿东</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">赐他一块白色石头，石头上写着新名</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://whitestore.top/2021/02/14/strategymodal/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="阿东">
      <meta itemprop="description" content="随遇而安">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱看书的阿东">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          浅谈设计模式 - 装饰器模式（五）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-02-14 11:40:16" itemprop="dateCreated datePublished" datetime="2021-02-14T11:40:16+08:00">2021-02-14</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-07-16 14:28:09" itemprop="dateModified" datetime="2023-07-16T14:28:09+08:00">2023-07-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">设计模式</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/02/14/strategymodal/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/02/14/strategymodal/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>9.2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>8 分钟</span>
            </span>
            <div class="post-description">设计模式装饰器模式</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="浅谈设计模式-装饰器模式（五）"><a href="#浅谈设计模式-装饰器模式（五）" class="headerlink" title="浅谈设计模式 - 装饰器模式（五）"></a>浅谈设计模式 - 装饰器模式（五）</h1><h2 id="前言："><a href="#前言：" class="headerlink" title="前言："></a>前言：</h2><p>​    装饰器模式是是对类进行增强的一种典型设计模式，它允许对于一个现有类进行增强的操作，对于喜欢使用继承的伙伴，这个模式非常贴切的展示的了对于继承的灵活用法。但是装饰器模式同样<strong>不是一个推崇使用的模式</strong>，因为他对于继承存在依赖性，从本文后续就可以了解到装饰类膨胀的问题，所以在设计代码结构的时候，装饰器模式<strong>并不是第一考虑</strong>。</p>
<a id="more"></a>

<h2 id="什么是装饰器模式？"><a href="#什么是装饰器模式？" class="headerlink" title="什么是装饰器模式？"></a>什么是装饰器模式？</h2><p>​    装饰器模式：对现有类不改动结构的情况下为类添加新职责和功能的模式。</p>
<p>​    动态的扩展类的职责，装饰器模式是一种是比继承更加灵活的代码扩展模式。同时装饰类之间可以进行互相的嵌套</p>
<h2 id="装饰器模式的结构图："><a href="#装饰器模式的结构图：" class="headerlink" title="装饰器模式的结构图："></a>装饰器模式的结构图：</h2><p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210207162333.png?ynotemdtimestamp=1613223296738" alt="img"></p>
<ul>
<li><p>Component 装饰接口</p>
<p>：装饰接口定义了装饰的顶层抽象行为，一般定义被装饰者和装饰者的公用行为</p>
<ul>
<li><p><strong>ConrecteComponent 被装饰类</strong>：主要为被装饰类实现，和装饰类相互独立，拥有单独的功能方法</p>
</li>
<li><p>Decorder 装饰器</p>
<p>：定义了装饰的通用接口，包含装饰器的通用方法</p>
<ul>
<li><strong>ConrecteDecorderA 装饰器A</strong>：定义了装饰器的具体设计，可以包含自己的装饰方法</li>
<li><strong>ConrecteDecorderB 装饰器B</strong>：定义了装饰器的具体设计，可以包含自己的装饰方法</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="装饰器模式的特点"><a href="#装饰器模式的特点" class="headerlink" title="装饰器模式的特点"></a>装饰器模式的特点</h2><ol>
<li>装饰者和被装饰者都需要实现<strong>相同的接口</strong>（必要条件）</li>
<li>装饰者一般需要继承一个抽象类，或者需要定义抽象的方法和实现</li>
<li>装饰者可以在所委托被装饰者的行为之前或之后，加上自己的行为，以达到特定的目的。</li>
<li><strong>任何父类出现的地方都可以用子类进行替换</strong>，在活用继承的同时可以灵活的扩展。</li>
</ol>
<h2 id="什么时候使用装饰器模式"><a href="#什么时候使用装饰器模式" class="headerlink" title="什么时候使用装饰器模式"></a>什么时候使用装饰器模式</h2><ul>
<li>需要大量的子类为某一个对象进行职责增强的时候，可以使用装饰器模式</li>
<li>希望使用继承对于类进行动态扩展的时候，可以考虑使用装饰器模式</li>
</ul>
<h2 id="实际案例："><a href="#实际案例：" class="headerlink" title="实际案例："></a>实际案例：</h2><h3 id="模拟场景："><a href="#模拟场景：" class="headerlink" title="模拟场景："></a>模拟场景：</h3><p>我们用一个奶茶的结构来模拟一个装饰器的设计场景，我们通常在奶茶店点奶茶的时候，对于一杯奶茶，可以添加各种配料，这时候配料就是奶茶的装饰者，而奶茶就是典型的被装饰者，我们使用配料去“装饰”奶茶，就可以得到各种口味的奶茶。同时可以计算出奶茶的价格</p>
<p>下面我们来看一下针对模拟场景的案例和使用：</p>
<h3 id="不使用设计模式："><a href="#不使用设计模式：" class="headerlink" title="不使用设计模式："></a>不使用设计模式：</h3><p>​    不使用设计模式，我们的第一考虑就是简单的使用继承去设计装饰类，我们通过各种子类组合来实现一杯杯不同口味的奶茶，从下面的结构图可以看到，将被装饰类定义为独立的类，同时不进行任何的继承而是作为独立的类使用。而调料也就是奶茶饮料的配料需要继承同一个抽象类，同时在内部实现自己的方法。</p>
<p>​    紧接着，我们在装饰者的方法中引入被装饰者，可以通过内部组合被装饰者进行 <strong>模仿</strong>行为的同时进行增强，就像IO当中的<code>Buffer</code>。</p>
<p>​    我们根据上面的说明画出这一种设计的大致结构图：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210207230255.png?ynotemdtimestamp=1613223296738" alt="img"></p>
<p>看了上面的设计图稿之后，我们来说明一下具体的代码实现：</p>
<p>首先是奶茶实体类：在奶茶的实体类里面定义两个属性， 使用一个<code>display()</code>打印信息，奶茶的实体类表示被装饰类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 奶茶实体类</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:21</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class MilkTea &#123;</span><br><span class="line"></span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    private double price;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public MilkTea(String name, double price) &#123;</span><br><span class="line">        this.name &#x3D; name;</span><br><span class="line">        this.price &#x3D; price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getName() &#123;</span><br><span class="line">        return name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setName(String name) &#123;</span><br><span class="line">        this.name &#x3D; name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public double getPrice() &#123;</span><br><span class="line">        return price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setPrice(double price) &#123;</span><br><span class="line">        this.price &#x3D; price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public void display() &#123;</span><br><span class="line">        System.out.println(&quot;name &#x3D; &quot;+ name + &quot; price &#x3D; &quot; +price);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>下面是柠檬汁的被装饰类，这个被装饰类也是独立的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 柠檬汁</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:53</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class LeamonJuice &#123;</span><br><span class="line"></span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    private double price;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public LeamonJuice(String name, double price) &#123;</span><br><span class="line">        this.name &#x3D; name;</span><br><span class="line">        this.price &#x3D; price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getName() &#123;</span><br><span class="line">        return name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setName(String name) &#123;</span><br><span class="line">        this.name &#x3D; name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public double getPrice() &#123;</span><br><span class="line">        return price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setPrice(double price) &#123;</span><br><span class="line">        this.price &#x3D; price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public void display() &#123;</span><br><span class="line">        System.out.println(&quot;name &#x3D; &quot;+ name + &quot; price &#x3D; &quot; +price);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调料的父类：注意这是一个抽象类，定义了调料的基本方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 调料父类</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:23</span><br><span class="line"> *&#x2F;</span><br><span class="line">public abstract class Codiment &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 为装饰类添加附加值</span><br><span class="line">     * @return</span><br><span class="line">     *&#x2F;</span><br><span class="line">    abstract void plusAdditionVal(MilkTea milkTea);</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 详细信息</span><br><span class="line">     *&#x2F;</span><br><span class="line">    protected String description()&#123;</span><br><span class="line">        return &quot;无任何配料&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调料的子类珍珠类，这里为父类进行装饰，添加父类的信息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 配料：珍珠</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:27</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class Pearl extends Codiment&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    void plusAdditionVal(MilkTea milkTea) &#123;</span><br><span class="line">        if(milkTea &#x3D;&#x3D; null)&#123;</span><br><span class="line">            throw new RuntimeException(&quot;对不起，请先添加奶茶&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        milkTea.setPrice(milkTea.getPrice() + 2);</span><br><span class="line">        milkTea.setName(milkTea.getName() + &quot;,&quot; +description());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 详细信息</span><br><span class="line">     *&#x2F;</span><br><span class="line">    protected String description()&#123;</span><br><span class="line">        return &quot;珍珠&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调料的子类椰果类，这里同样是为了父类进行装饰的方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 配料：椰果</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:30</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class Coconut extends Codiment&#123;</span><br><span class="line">    @Override</span><br><span class="line">    void plusAdditionVal(MilkTea milkTea) &#123;</span><br><span class="line">        if(milkTea &#x3D;&#x3D; null)&#123;</span><br><span class="line">            throw new RuntimeException(&quot;对不起，请先添加奶茶&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        milkTea.setPrice(milkTea.getPrice() + 1);</span><br><span class="line">        milkTea.setName(milkTea.getName() + &quot;,&quot; +description());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected String description() &#123;</span><br><span class="line">        return &quot;椰果&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后我们使用一个单元测试：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 单元测试</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:34</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class Main &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        MilkTea milkTea &#x3D; new MilkTea(&quot;原味奶茶&quot;, 5);</span><br><span class="line">        Pearl pearl &#x3D; new Pearl();</span><br><span class="line">        Coconut coconut &#x3D; new Coconut();</span><br><span class="line">        pearl.plusAdditionVal(milkTea);</span><br><span class="line">        coconut.plusAdditionVal(milkTea);</span><br><span class="line">        milkTea.display();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;&#x2F;*</span><br><span class="line">打印结果：name &#x3D; 原味奶茶,珍珠,椰果 price &#x3D; 8.0</span><br><span class="line">*&#x2F;</span><br></pre></td></tr></table></figure>

<h3 id="不使用设计模式的优缺点："><a href="#不使用设计模式的优缺点：" class="headerlink" title="不使用设计模式的优缺点："></a>不使用设计模式的优缺点：</h3><p>优点：</p>
<ul>
<li>添加一个装饰者十分简单，只需要继承抽象父类接口，同时子类只需要通过方法传入被装饰者进行装饰。</li>
</ul>
<p>缺点：</p>
<ul>
<li>我们的调料父类如果<strong>增加抽象方法</strong>，<strong>所有的子类都需要改动</strong>，这是整个子类群体来说是毁灭性的，对于编写代码的程序员来说也是毁灭性的。</li>
<li>可以看到装饰者已经是一种<strong>面向实现编程</strong>的状态，如果我们换一种被装饰者，需要添加更多的装饰类进行装饰。并且这些装饰者是<strong>相互独立并且不能复用的</strong></li>
</ul>
<blockquote>
<p>从结构图的设计就可以看出这种设计不符合<strong>面向接口编程</strong>的设计原则</p>
</blockquote>
<h3 id="总结不使用模式："><a href="#总结不使用模式：" class="headerlink" title="总结不使用模式："></a>总结不使用模式：</h3><p>​    不使用设计模式看起来没有什么大问题，但是可以从结构可以看到抽象父类以及子类的耦合过于严重，父类完全不敢动<code>abstract void plusAdditionVal(MilkTea milkTea)</code>这个抽象签名方法，并且如果需求增加一个其他的被装饰者，这些装饰奶茶的装饰者就完全“傻眼”了，因为他们完全不认识新的被装饰者，这导致程序要更多的子类来接纳新的的被装饰者，这种设计结构将导致类<strong>子类无限膨胀</strong>，没有尽头。</p>
<h3 id="使用设计模式："><a href="#使用设计模式：" class="headerlink" title="使用设计模式："></a>使用设计模式：</h3><p>​    从不使用设计模式可以看出，不使用设计模式最大的问题是在于调料的父类抽象方法耦合过于严重，以及被装饰类和装饰者之间存在依赖磁铁。从结构图可以看出来被装饰类和装饰类<strong>并没有明显的关联</strong>，我们之前已经说明了装饰模式更多的是对于一个被装饰类的增强，既然是增强，那么<strong>被装饰类和装饰类通常需要具备相同的抽象行为</strong>，这样才比较符合装饰模式的设计结构。</p>
<p>​    下面就上面的结构图进行改进，在 <strong>被装饰类</strong>和<strong>装饰类</strong>之上，再增加一层接口，调料的父类不在管理公用接口，而是可以增加自己的方法。我们改进一下结构图，只要稍微改进一下，整个结构就可以变得十分好用：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210208001255.png?ynotemdtimestamp=1613223296738" alt="img"></p>
<p>为了方便展示代码和理解，这里只列出了<strong>奶茶类</strong>，<strong>调料父类</strong>，<strong>配料：珍珠</strong>，以及我们最重要的公用接口进行介绍：</p>
<p>我们从最顶层开始，最顶层在结构上定义了一个抽象公用接口，提供装饰者以及被装饰者进行实现或者定义抽象和扩展：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 饮料的抽象类，定义饮料的通用接口</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 23:46</span><br><span class="line"> *&#x2F;</span><br><span class="line">public interface DrinkAbstract &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 装饰接口</span><br><span class="line">     *&#x2F;</span><br><span class="line">    void plusAdditionVal();</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 计算售价</span><br><span class="line">     * @return</span><br><span class="line">     *&#x2F;</span><br><span class="line">    double coat();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后是奶茶类，我们的奶茶类在上一个版本基础上，实现了一个新的接口，所以需要定义实现接口后的方法：</p>
<p>奶茶类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 奶茶实体类</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:21</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class MilkTea implements DrinkAbstract&#123;</span><br><span class="line"></span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    private double price;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public MilkTea(String name, double price) &#123;</span><br><span class="line">        this.name &#x3D; name;</span><br><span class="line">        this.price &#x3D; price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getName() &#123;</span><br><span class="line">        return name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setName(String name) &#123;</span><br><span class="line">        this.name &#x3D; name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public double getPrice() &#123;</span><br><span class="line">        return price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setPrice(double price) &#123;</span><br><span class="line">        this.price &#x3D; price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public void display() &#123;</span><br><span class="line">        System.out.println(&quot;name &#x3D; &quot;+ name + &quot; price &#x3D; &quot; +price);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 增加</span><br><span class="line">    @Override</span><br><span class="line">    public void plusAdditionVal() &#123;</span><br><span class="line">        System.out.println(&quot;name &#x3D; &quot;+ name  + &quot; price &#x3D; &quot; + price);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 增加</span><br><span class="line">    @Override</span><br><span class="line">    public double coat() &#123;</span><br><span class="line">        return price;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>下面是调料的父类，调料的父类需要改动的内容不是很多，本质上就是把自己的抽象方法提取到父接口。这个类可以是抽象类，也可以是配料接口的通用抽象：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 调料父类</span><br><span class="line"> * 这里需要实现饮料接口</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:23</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class Codiment implements DrinkAbstract&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 为装饰类添加附加值</span><br><span class="line">     * @return</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public void plusAdditionVal()&#123;</span><br><span class="line">        description();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public double coat() &#123;</span><br><span class="line">        return 5.0f;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 详细信息</span><br><span class="line">     *&#x2F;</span><br><span class="line">    private String description()&#123;</span><br><span class="line">        return &quot;无任何配料&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后是配料的具体实现类配料-珍珠进行改动：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 配料：珍珠</span><br><span class="line"> *</span><br><span class="line"> * @author zxd</span><br><span class="line"> * @version 1.0</span><br><span class="line"> * @date 2021&#x2F;2&#x2F;7 22:27</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class Pearl extends Codiment implements DrinkAbstract&#123;</span><br><span class="line"></span><br><span class="line">    private DrinkAbstract drinkAbstract;</span><br><span class="line"></span><br><span class="line">    public Pearl(DrinkAbstract drinkAbstract) &#123;</span><br><span class="line">        this.drinkAbstract &#x3D; drinkAbstract;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void plusAdditionVal() &#123;</span><br><span class="line">        &#x2F;&#x2F; 如果是奶茶</span><br><span class="line">        if(drinkAbstract instanceof MilkTea)&#123;</span><br><span class="line">            MilkTea drinkAbstract &#x3D; (MilkTea) this.drinkAbstract;</span><br><span class="line">            drinkAbstract.setName(drinkAbstract.getName() + &quot; -- &quot; + &quot;珍珠&quot;);</span><br><span class="line">            drinkAbstract.setPrice(drinkAbstract.getPrice() + 55);</span><br><span class="line">            description();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public double coat() &#123;</span><br><span class="line">        return 5;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 详细信息</span><br><span class="line">     *&#x2F;</span><br><span class="line">    private void description()&#123;</span><br><span class="line">        drinkAbstract.plusAdditionVal();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后，我们来看下单元测试的变化：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public class Main &#123;</span><br><span class="line">    private static void run2()&#123;</span><br><span class="line">        DrinkAbstract drinkAbstract &#x3D; new MilkTea(&quot;原味奶茶&quot;, 5);</span><br><span class="line">        Pearl codiment &#x3D; new Pearl(drinkAbstract);</span><br><span class="line">        codiment.plusAdditionVal();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">       run2();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;&#x2F;*控制台结果：name &#x3D; 原味奶茶 -- 珍珠 price &#x3D; 60.0*&#x2F;</span><br></pre></td></tr></table></figure>

<p>可以看到我们使用装饰类对于被装饰类的属性进行了改变的同时并没有改变被装饰者的本身的行为，而是对于行为做了扩展。</p>
<h3 id="使用装饰器设计模式的优缺点："><a href="#使用装饰器设计模式的优缺点：" class="headerlink" title="使用装饰器设计模式的优缺点："></a>使用装饰器设计模式的优缺点：</h3><p>优点：</p>
<ol>
<li>装饰类的公用类不再需要设置抽象的方法，使得装饰实现子类也不在依赖抽象父类的抽象方法</li>
<li>既然装饰者和被装饰对象有相同的超类型，所以在任何需要原始对象（被包装的）的场合，就可以用装饰过的对象代替它。</li>
<li>装饰类和被装饰类的扩展和实现都是解耦的，不需要互相关注实现细节，装饰子类可以独自实现方法</li>
<li>我们解决了增加新的被装饰类之后导致装饰类大量膨胀的问题，现在可以进行简单的应用。</li>
</ol>
<p>缺点：</p>
<ol>
<li>本质上还是继承结构，而且装饰类和被装饰类<strong>必须</strong>有相同的顶级父类接口</li>
<li>装饰类在系统越来越复杂之后会出现明显的膨胀。</li>
</ol>
<h2 id="JAVA-IO-典型的装饰模式："><a href="#JAVA-IO-典型的装饰模式：" class="headerlink" title="JAVA IO - 典型的装饰模式："></a>JAVA IO - 典型的装饰模式：</h2><p>​    首先说明<code>JAVA IO</code>类其实本质上<strong>并不是一个十分优秀的设计</strong>（因为复杂的装饰子类和API结构），这个问题可以查看《JAVA编程思想》作者对于JAVA IO复杂难用的API以及继承结构进行过的一系列吐槽，而且JAVA IO经过后面版本的迭代改进。使得原本的方法更加复杂多变，但是不管JAVA IO设计的API如何不“便民”，这一块的设计依然是非常值得学习和思考的，也是装饰模式最典型的使用。</p>
<p>​    下面为一张《Head First设计模式的一张图》说明一下JAVA IO装饰设计的装饰器膨胀问题:</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210208114348.png?ynotemdtimestamp=1613223296738" alt="img"></p>
<blockquote>
<ul>
<li>可以看到InputStream是一个抽象类。</li>
<li>在<strong>JDK1.5</strong>当中，他扩展自接口<code>java.io.Closeable</code>，规定需要接入装饰的类需要实现自己的流关闭方法。</li>
<li>在<strong>JDK1.7</strong> 中，在<code>Closeable</code>基础上增加了<code>java.io.AutoClosable</code>来实现流的<strong>自动关闭</strong>功能。</li>
</ul>
</blockquote>
<p>从上面的图标也可以看到装饰器的一些缺点：</p>
<ol>
<li>装饰类之间的具有复杂的继承结构</li>
<li>装饰者之间虽然<strong>可以互相嵌套，但是不一定互相兼容</strong></li>
</ol>
<blockquote>
<p>JAVA IO对于JAVA初学者来说十分不友好，从其他语言可以看到吸取了这一点的教训，通常都把IO流这一块设计的越简单好用越好（尽量的让调用者不需要去思考IO流的细节问题）。而JAVA IO 显然设计的不是很亲民。</p>
</blockquote>
<h1 id="总结装饰器模式："><a href="#总结装饰器模式：" class="headerlink" title="总结装饰器模式："></a>总结装饰器模式：</h1><h2 id="优点："><a href="#优点：" class="headerlink" title="优点："></a>优点：</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">+ 装饰者和被装饰对象有相同的接口。</span><br><span class="line">+ 可以用一个或多个装饰者包装一个被装饰对象或者被装饰对象。</span><br><span class="line">+ 既然装饰者和被装饰对象有相同的超类型，所以在任何需要原始对象（被包装的）的场合，可以用装饰过的对象代替它。</span><br><span class="line">+ 装饰者可以在所委托被装饰者的行为之前或之后，加上自己的行为，以达到特定的目的。</span><br><span class="line">+ 装饰者可以无限的嵌套，因为他们本质上归属于同一个接口</span><br></pre></td></tr></table></figure>

<h2 id="缺点："><a href="#缺点：" class="headerlink" title="缺点："></a>缺点：</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+ 装饰者很容易出现大量的小类，这让了解代码的人不容易清楚不同装饰的设计</span><br><span class="line">+ 一个依赖其他具体类型的接口导入装饰者可能会带来灾难。所以导入装饰者要非常小心谨慎，并且仔细考虑是否真的需要装饰者模式</span><br><span class="line">+ 装饰者互相嵌套可能会增加代码的复杂度，也增加扩展装饰者子类的复杂度，最终这个难题会变成调用者的难题</span><br></pre></td></tr></table></figure>

<h1 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h1><p>​    许多的设计模式书籍都警告过装饰器模式是一个需要<strong>谨慎考虑</strong>的设计模式，因为装饰模式很容易会造成装饰类的膨胀，同时对于特定类型接入装饰类可能会有意想不到的灾难，同时在接入装饰类的时候，需要仔细的了解公用接口和抽象类的实现，需要了解这一类装饰针对的行为，否则只是简单的继承装饰父类或者继承接口可能会有一些莫名其妙的问题。</p>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>lazytime
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://whitestore.top/2021/02/14/strategymodal/" title="浅谈设计模式 - 装饰器模式（五）">https://whitestore.top/2021/02/14/strategymodal/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLzQuMC96aC1DTg=="><i class="fa fa-fw fa-creative-commons"></i>BY-NC</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag"># 设计模式</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/02/14/mofeidinglv/" rel="prev" title="《墨菲定律》读书笔记">
      <i class="fa fa-chevron-left"></i> 《墨菲定律》读书笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/02/14/nativebook/" rel="next" title="《生活需要断舍离》读书笔记">
      《生活需要断舍离》读书笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#浅谈设计模式-装饰器模式（五）"><span class="nav-number">1.</span> <span class="nav-text">浅谈设计模式 - 装饰器模式（五）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言："><span class="nav-number">1.1.</span> <span class="nav-text">前言：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是装饰器模式？"><span class="nav-number">1.2.</span> <span class="nav-text">什么是装饰器模式？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#装饰器模式的结构图："><span class="nav-number">1.3.</span> <span class="nav-text">装饰器模式的结构图：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#装饰器模式的特点"><span class="nav-number">1.4.</span> <span class="nav-text">装饰器模式的特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么时候使用装饰器模式"><span class="nav-number">1.5.</span> <span class="nav-text">什么时候使用装饰器模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实际案例："><span class="nav-number">1.6.</span> <span class="nav-text">实际案例：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#模拟场景："><span class="nav-number">1.6.1.</span> <span class="nav-text">模拟场景：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不使用设计模式："><span class="nav-number">1.6.2.</span> <span class="nav-text">不使用设计模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不使用设计模式的优缺点："><span class="nav-number">1.6.3.</span> <span class="nav-text">不使用设计模式的优缺点：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结不使用模式："><span class="nav-number">1.6.4.</span> <span class="nav-text">总结不使用模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用设计模式："><span class="nav-number">1.6.5.</span> <span class="nav-text">使用设计模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用装饰器设计模式的优缺点："><span class="nav-number">1.6.6.</span> <span class="nav-text">使用装饰器设计模式的优缺点：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JAVA-IO-典型的装饰模式："><span class="nav-number">1.7.</span> <span class="nav-text">JAVA IO - 典型的装饰模式：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结装饰器模式："><span class="nav-number">2.</span> <span class="nav-text">总结装饰器模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#优点："><span class="nav-number">2.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缺点："><span class="nav-number">2.2.</span> <span class="nav-text">缺点：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结："><span class="nav-number">3.</span> <span class="nav-text">总结：</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">阿东</p>
  <div class="site-description" itemprop="description">随遇而安</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">239</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">36</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lazyTimes"><i class="fa fa-fw fa-github"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjEwOTc0ODM1MDhAcXEuY29t" title="E-Mail → mailto:1097483508@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly93d3cuNTJwb2ppZS5jbi9ob21lLnBocD9tb2Q9c3BhY2UmdWlkPTE0OTc3MTgmZG89dGhyZWFkJnZpZXc9bWUmZnJvbT1zcGFjZQ==" title="https:&#x2F;&#x2F;www.52pojie.cn&#x2F;home.php?mod&#x3D;space&amp;uid&#x3D;1497718&amp;do&#x3D;thread&amp;view&#x3D;me&amp;from&#x3D;space">吾爱破解</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9qdWVqaW4uaW0vdXNlci8yOTk5MTIzNDUyNjI2MzY2" title="https:&#x2F;&#x2F;juejin.im&#x2F;user&#x2F;2999123452626366">掘金</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9zZWdtZW50ZmF1bHQuY29tL3UvbGF6eXRpbWVz" title="https:&#x2F;&#x2F;segmentfault.com&#x2F;u&#x2F;lazytimes">思否</span>
        </li>
    </ul>
  </div>

      </div>

      <div class="wechat_OA">
        <span>欢迎关注我的公众号</span>
        <br>
          <!-- 这里添加你的二维码图片 -->
        <img src ="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/wechat_channel.jpg">
      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">阿东</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">2m</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">29:50</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'qMUpEEvBgXaMDD1b0ftgi9xr-gzGzoHsz',
      appKey     : 'UCdfT4Rfih6MO6y8DI4fstf6',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
